/**   
 * @Title: MainActivityExpertAppointFragment.java 
 * @Package cn.edu.scu.healthclient.activity.fragment 
 * @Description: TODO 
 * @author 
 * @date 
 * @version V0.0   
 */
package cn.edu.cdtu.healthclient.activity.fragment;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.cdtu.healthclient.activity.MainActivity;
import cn.edu.cdtu.healthclient.connect.DoctorService;
import cn.edu.cdtu.healthclient.connect.SendService;
import cn.edu.cdtu.healthclient.domain.Doctor;
import cn.edu.cdtu.healthclient.domain.Register;
import cn.edu.cdtu.healthclient.utils.ConnectUtil.HealthDoctorRegister;
import cn.edu.scu.healthclient.activity.R;

/** 
 * @ClassName: MainActivityExpertAppointFragment 
 * @Description: TODO
 * @author 
 * @date 
 *  
 */
public class MainActivityExpertAppointFragment extends Fragment {

	private Spinner spinner_dep;
	private Spinner spinner_name;
	private TextView textView_intro;

	private ArrayAdapter<String> adapter_dep;
	private ArrayAdapter<String> adapter_name;

	private String[] departmentNames = null;

	private String[] departmentName = {"男科","妇科","妇产科"};
	private String[] doctorName1 = new String[]{"李鹏","李程鹏"};
	private String[] doctorName2 = new String[]{"李四"};
	private String[] doctorName3 = new String[]{"赵五"};
	private String[] doctorDes = new String[]{"这个也是治不好的","你治不好的","李程鹏治不好","这个医生是个水货"};
	//private	String[][] doctorNames = new String [6][5];
	private SparseArray<String[]> doctorNames = new SparseArray<String[]>();
	private SparseArray<String[]> doctorIntro = new SparseArray<String[]>();
	private SparseArray<Integer[]> doctorId = new SparseArray<Integer[]>();
	private String[] doctorintroArray = null;
	private Integer[] doctorIdArray = null;

	private List<Doctor> doctors;

	//设置返回值
	private java.util.Date regDate ;
	private int regDoctorId;
	private class DepartmentSet{
		public String departmentName;
		public List<Doctor> doctorList = new ArrayList<Doctor>();
		/** 
		 * @Title: DepartmentSet
		 * @Description: TODO
		 * @throws 
		 *
		 * @param departmentName
		 */
		public DepartmentSet(String departmentName) {
			this.departmentName = departmentName;
		}

	}

	private List<DepartmentSet> departmentList = new ArrayList<DepartmentSet>();

	private TextView topTitle;

	/* (non-Javadoc)
	 * <p>Title: onActivityCreated</p> 
	 * <p>Description: </p> 
	 * @param savedInstanceState 
	 * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads()
		.detectDiskWrites()
		.detectNetwork() // 这里可以替换为detectAll() 就包括了磁盘读写和网络I/O
		.penaltyLog() //打印logcat，当然也可以定位到dropbox，通过文件保存相应的log
		.build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		.detectLeakedSqlLiteObjects() //探测SQLite数据库操作
		.penaltyLog() //打印logcat
		.penaltyDeath()
		.build()); 
		super.onActivityCreated(savedInstanceState);
		topTitle = (TextView) getView().findViewById(R.id.topTitle);  
		topTitle.setText("专家预约");
		spinner_name = (Spinner) getView().findViewById(R.id.re_spinner02);
		textView_intro = (TextView) getView().findViewById(R.id.re_View);
		spinner_dep = (Spinner) getView().findViewById(R.id.re_spinner01);
		Button button = (Button) getView().findViewById(R.id.re_Button);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				((MainActivity)getActivity()).getTaskQueue().addTask(
						new Thread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								try {
									Register reg = new Register();
									reg.setD_id(regDoctorId);
									reg.setDate(regDate);
									final boolean isSend = 
											SendService.sendReg(
													((MainActivity)getActivity())
													.getBinder().getHttpClient(), 
													"sendReg", reg);
									getActivity().runOnUiThread(new Runnable() {

										@Override
										public void run() {
											// TODO Auto-generated method stub
											String reg_succeed = "预约成功";
											String reg_fail = "预约失败";
											if (isSend) {
												Toast.makeText(getActivity(), 
														reg_succeed , 
														Toast.LENGTH_SHORT).show();
											}
											else {
												Toast.makeText(getActivity(),
														reg_fail , 
														Toast.LENGTH_SHORT).show();
											}
										}
									});
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}));
			}
		});
		final EditText datePick = (EditText) getView().findViewById(R.id.pick_time);
		datePick.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					Calendar c = Calendar.getInstance();
					// 直接创建一个DatePickerDialog对话框实例，并将它显示出来
					new DatePickerDialog(getActivity(),
							// 绑定监听器
							new DatePickerDialog.OnDateSetListener()
					{
						@SuppressWarnings("deprecation")
						@Override
						public void onDateSet(DatePicker dp, int year,
								int month, int dayOfMonth)
						{
							datePick.setText("您选择了：" + year + "年" + (month + 1)
									+ "月" + dayOfMonth + "日");
							regDate = new java.util.Date(year-1900,month,dayOfMonth);
						}
					}
					//设置初始日期
					, c.get(Calendar.YEAR)
					, c.get(Calendar.MONTH)
					, c.get(Calendar.DAY_OF_MONTH)).show();
					break;
				case MotionEvent.ACTION_UP:
					v.performClick();
					break;
				default:
					break;
				}
				return true;
			}
		});
		((MainActivity)getActivity()).getTaskQueue().addTask(
				new Thread(new DoctorTaskImplementation()));
	}

	/* (non-Javadoc)
	 * <p>Title: onCreateView</p> 
	 * <p>Description: </p> 
	 * @param inflater
	 * @param container
	 * @param savedInstanceState
	 * @return 
	 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(
				R.layout.activity_main_expertappoint_fragment, container, false);
	}

	/**
	 * 
	 * @ClassName: DoctorTaskImplementation 
	 * @Description: TODO
	 * @author 
	 * @date 
	 *
	 */
	private class DoctorTaskImplementation implements Runnable{

		/* (non-Javadoc)
		 * <p>Title: run</p> 
		 * <p>Description: </p>  
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				
//				Doctor doctor1 = new Doctor(1, "李鹏", "这个也是治不好的", "妇科", 1);
//				Doctor doctor2 = new Doctor(2, "李程鹏", "你治不好的", "男科", 1);
//				Doctor doctor3 = new Doctor(3, "李四", "李程鹏治不好", "妇科", 2);
//				Doctor doctor4 = new Doctor(4, "李四", "这个医生是个水货", "妇产科", 3);
//				doctors.add(doctor1);
//				doctors.add(doctor2);
//				doctors.add(doctor3);
//				doctors.add(doctor4);
				doctors = DoctorService.getJSONDoctors(
						((MainActivity)getActivity()).getBinder().getHttpClient(),
						HealthDoctorRegister.Option.OptionValue.GET_DOCTOR_LIST);
				for (Doctor doctor : doctors) {
					DepartmentSet tempSet = null;
					//					遍历所有科室列表
					for(DepartmentSet departmentSet:departmentList){
						//						如果科室列表有的话，直接使用当前列表
						if(doctor.getDepartment().equals(departmentSet.departmentName)){
							tempSet = departmentSet;
							break;
						}
					}
					//					如果科室列表没有的话，创建一个新的科室列表
					if (tempSet == null) {
						tempSet = new DepartmentSet(doctor.getDepartment());
						departmentList.add(tempSet);
					}
					//					将医生添入各自的科室中
					
					tempSet.doctorList.add(doctor);
				}
				//科室数组生成
				List<String> departmentNameList = new ArrayList<String>();
				for(DepartmentSet departmentSet:departmentList){
					departmentNameList.add(departmentSet.departmentName);
				}
				departmentNames = departmentNameList.toArray(
						new String[departmentNameList.size()]);
				for(int i = 0; i< departmentNames.length;i++){

					String departmentName = departmentNames[i];
					for (DepartmentSet departmentSet : departmentList) {
						if(departmentSet.departmentName.equals(departmentName)){
							List<String> doctorNameList = new ArrayList<String>();
							List<String> doctorIntroList = new ArrayList<String>();
							List<Integer> doctorIdList = new ArrayList<Integer>();
							for(Doctor doctor:departmentSet.doctorList){
								doctorNameList.add(doctor.getName());
								doctorIntroList.add(doctor.getIntroduction());
								doctorIdList.add(Integer.valueOf(doctor.getId()));
							}
							String[] nameStrings =(String[])doctorNameList.toArray(new String[doctorNameList.size()]);
							String[] introStrings = (String[])doctorIntroList.toArray(new String[doctorNameList.size()]);
							Object[] doctorIdObj = doctorIdList.toArray();
							Integer[] doctorIdint = new Integer[doctorIdList.size()];
							for(int m = 0; m <doctorIdList.size();m++){
								doctorIdint[m] = Integer.parseInt(String.valueOf(doctorIdObj[m]));
							}
							doctorNames.put(i, nameStrings);
							doctorIntro.put(i, introStrings);
							doctorId.put(i,  doctorIdint);
						}
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					adapter_dep = new ArrayAdapter<String>(getActivity(), 
							android.R.layout.simple_list_item_multiple_choice,
							departmentName);
					spinner_dep.setAdapter(adapter_dep);
					//					监听第一个菜单
					spinner_dep.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
						@Override
						public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
							// TODO Auto-generated method stub
							int dep = position;
							//设置显示当前选择的项
							doctorintroArray = doctorIntro.get(dep);
							doctorIdArray = doctorId.get(dep);
							
							final String d_n = departmentName[dep];
							
							if(dep == 0){
								adapter_name = new ArrayAdapter<String>(
										getActivity(),
										android.R.layout.simple_list_item_multiple_choice,
										doctorName1);
							}else if(dep == 1){
								adapter_name = new ArrayAdapter<String>(
										getActivity(),
										android.R.layout.simple_list_item_multiple_choice,
										doctorName2);
							}else if(dep == 2){
								adapter_name = new ArrayAdapter<String>(
										getActivity(),
										android.R.layout.simple_list_item_multiple_choice,
										doctorName3);
							}
//							adapter_name = new ArrayAdapter<String>(
//									getActivity(),
//									android.R.layout.simple_list_item_multiple_choice,
//									doctorNames.get(dep));
							spinner_name.setAdapter(adapter_name);
							//							  监听第二个菜单
							spinner_name.setOnItemSelectedListener(
									new Spinner.OnItemSelectedListener(){
										@Override
										public void onItemSelected(AdapterView<?> parent, View view,
												int position, long id) {
											// TODO Auto-generated method stub
											int dep2 = position;
											//设置显示当前选择的项
//											parent.setVisibility(View.VISIBLE);
//											String doctorIntro = doctorintroArray[dep2];
											String d_na;
											if(d_n.equals("男科") && position == 0){
												textView_intro.setText(
														"医生简介:\n"+"      \n"+ "这个也是治不好的");
											} else if(d_n.equals("男科") && position == 1){
												textView_intro.setText(
														"医生简介:\n"+"      \n"+ "你治不好的");
											}else if(d_n.equals("妇科") && position == 0){
												textView_intro.setText(
														"医生简介:\n"+"      \n"+ "李程鹏治不好");
											}else if(d_n.equals("妇产科") && position == 0){
												textView_intro.setText(
														"医生简介:\n"+"      \n"+ "这个医生是个水货");
											}
										    
//										    regDoctorId = doctorIdArray[dep2];
//											textView_intro.setText(
//													"医生简介:\n"+"      \n" + doctorIntro );

										    
											
											

										}

										@Override
										public void onNothingSelected(AdapterView<?> parent) {
											// TODO Auto-generated method stub
										}

									});
						}

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
							// TODO Auto-generated method stub
						}
					});
				}
			});
		}

	}
}
